package threads;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;

import nlp.NamedEntityRecognizer;

public class NER_Query implements Runnable{
	
	String SQL;
	NamedEntityRecognizer ner;
	Connection conn;
	ResultSet result;
	String threadname;
	final int batchSize = 1000;  
	
	public NER_Query(String SQL_, Connection conn_, NamedEntityRecognizer ner_, String threadname_){
		this.SQL = SQL_;
		this.ner = ner_;
		this.conn = conn_;
		this.threadname = threadname_;
	}
	
    @Override
    public void run() {
    	Statement statement;
		try {
			statement = conn.createStatement();
			ResultSet resultSet = statement.executeQuery(SQL);
			int count = 0;
			
			//news and blogs
			//resultSet.setFetchSize(449208);
			//String SQL_INSERT = "INSERT INTO content_named_entities (id_content, title_ner, body_ner) VALUES (?,?,?)";
			
			//comments
			resultSet.setFetchSize(13423);			
			String SQL_INSERT = "INSERT INTO comment_named_entities (id_comment, comment_tagged) VALUES (?,?)";
			
			PreparedStatement ps = this.conn.prepareStatement(SQL_INSERT);
			while (resultSet.next()) {

				/* news a blogs
				int id = resultSet.getInt(1);
				String title = resultSet.getString(5);
				String body = resultSet.getString(6);				
				String title_xml = ner.tagXML(title);
				String body_xml = ner.tagXML(body);				
				ps.setInt(1,id);
				ps.setString(2, title_xml);
				ps.setString(3, body_xml);
				*/

				//comments
			 	int id = resultSet.getInt(1);
			 	String comments = resultSet.getString(2);
			 	String comments_xml = ner.tagText(comments);
				ps.setInt(1,id);
				ps.setString(2, comments_xml);
				
				ps.addBatch();
				if(++count % batchSize == 0) {
			        int[] updates = ps.executeBatch();
			        int z = 0;
			        for (int i : updates) {
						z += updates[i];
					}
			        //System.out.println(":: " + this.threadname + " tagged " + count + "/"+"449208" + " articles");
			        System.out.println(":: " + this.threadname + " tagged " + count + "/"+"13420" + " articles");
			    }
	        }
			ps.executeBatch(); // insert remaining records
			this.conn.commit();
			ps.close();
			System.out.println(this.threadname + " finished");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();		        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}